import Taro from "@tarojs/taro";

/**
 * 显示消息提示框
 * @param content 提示的标题
 */
export function toast(content) {
  Taro.showToast({
    icon: "none",
    title: content,
    duration: 2000,
  });
}

/**
 * 显示模态弹窗
 * @param content 提示的标题
 */
export function showConfirm(content) {
  return new Promise((resolve, reject) => {
    Taro.showModal({
      title: "提示",
      content: content,
      cancelText: "取消",
      confirmText: "确定",
      success: function (res) {
        resolve(res);
      },
    });
  });
}

// 判断文本输入是否为空
export const isEmpty = (str) => {
  return str.trim() == "";
};

/**
 * 匹配phone
 */
export const isMobile = (str) => {
  const reg = /^(1[3456789]\d{9})$/;
  return reg.test(str);
};

/**
 * 校验身份证
 */
export const isIdCardNum = (str) => {
  let _IDRe18 =
    /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  let _IDre15 =
    /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/;
  return _IDRe18.test(str) || _IDre15.test(str);
};

/**
 * 校验真实姓名
 */
export const isRealName = (str) => {
  let reg = /^[\u4E00-\u9FA5]{2,10}(·[\u4E00-\u9FA5]{2,10}){0,2}$/;
  return reg.test(str);
};

/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null  && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== "" &&
            typeof value[key] !== "undefined"
          ) {
            let params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time
        .replace(new RegExp(/-/gm), "/")
        .replace("T", " ")
        .replace(new RegExp(/\.\d{3}/gm), "");
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

//计算文件大小
export function getFileSize(size) {
  if (!size) {
    return "0KB";
  }
  if (parseFloat(size) < 1024) {
    return `${size}B`;
  }
  if (parseFloat(size) / 1024 < 1024) {
    return `${(parseFloat(size) / 1024).toFixed(1)}KB`;
  }
  return `${(parseFloat(size) / 1024 / 1024).toFixed(1)}MB`;
}

//格式化金钱
export function formatMoney(v) {
  if (!v) return null;
  let value = String(v);
  var valueArr = value.split(".")[0].split("").reverse();
  const valueFloat = value.split(".")[1];
  let valueString = "";
  for (let i = 0; i < valueArr.length; i++) {
    valueString +=
      valueArr[i] + ((i + 1) % 3 == 0 && i + 1 != valueArr.length ? "," : "");
  }
  const money = valueFloat
    ? valueString.split("").reverse().join("") + "." + valueFloat
    : valueString.split("").reverse().join("");
  return money;
}

/**
 * scroll-view区域的高度是进入页面动态计算的
 * @returns {number} scrollHeight
 */
export function computeContentHeight(className) {
  return new Promise((resolve, reject) => {
    let doms = Taro.createSelectorQuery().selectAll(
      className ? className : ".scrollview"
    );
    doms
      .fields(
        {
          rect: true, //是否返回节点布局位置信息{left,top,right,bottom}
        },
        function (res) {
          resolve(Taro.getSystemInfoSync().windowHeight - res[0].top);
          //res 可以返回第一个参数对象中指定为true的相关信息
        }
      )
      .exec(function () {
        //上述节点信息获取成功后执行的回调函数
      });
  });
}
export function computeContentTop(className) {
  return new Promise((resolve, reject) => {
    let doms = Taro.createSelectorQuery().selectAll(className);
    doms
      .fields(
        {
          rect: true, //是否返回节点布局位置信息{left,top,right,bottom}
        },
        function (res) {
          resolve(res[0].top);
          //res 可以返回第一个参数对象中指定为true的相关信息
        }
      )
      .exec(function () {
        //上述节点信息获取成功后执行的回调函数
      });
  });
}

export function getTabbarHeight() {
  let sys = Taro.getSystemInfoSync();
  return (sys.windowHeight - sys.safeArea.bottom + 50) * 2 + "rpx";
}

export function flushUserInfo() {
  return new Promise((resolve, reject) => {
    Taro.getCurrentInstance()
      .dva.dispatch({
        type: "user/fetchGetUserInfo",
      })
      .then((res) => {
        console.log("fetchGetUserInfo", res);
        resolve(res);
      });
  });
}
